<?php
namespace App\Model;

use Hyperf\Utils\Collection;
use Hyperf\Database\Model\Model;

class BaseModel extends Model
{
    public $model;

    public function __construct($model)
    {
        parent::__construct();
        $this->model = new $model;
    }

    public function getInstance(){
        return $this->model;
    }
    /**
     * 更复杂的结构 建议自己用 MODEL 实例重新编写  参数传递太多太丑
     * @param array $where  ['id' => 1]
     * @param array $orderBy ['id'=> 'desc','sort' => 'asc']
     * @param array $select  ['id’,'name']
     * @return Collection
     */
    public function getModelLists(?array $where = [],?array $select = ['*'],?array $orderBy = []):Collection
    {
        $model = $this->model;
        $model = $model->where($where)->select($select);
        if(!empty($orderBy)){
            foreach ($orderBy as $key => $item){
                $model->orderBy($key,$item);
            }
        }
        return $model->get();
    }

    /**
     * 获取详情  注意条件不存在会返回NULL
     * @param array $where
     * @return mixed
     */
    public function getModelDetail(array $where = [],array $select = ['*'])
    {
        return $this->model->select($select)->where($where)->first();
    }

    /**
     * 查询模型数据是否存在
     * @param array $where
     * @return Collection
     */
    public function getModelExists(array $where)
    {
        return $this->model->where(where)->exists();
    }


    /**
     * 查询模型数据是否存在
     * @param array $where
     * @return Collection
     */
    public function getModelCount(array $where)
    {
        return $this->model->where(where)->count();
    }


    /**
     * 创建数据
     * @param array $data
     * @return Collection
     */
    public function createModel(array $data)
    {
        return $this->model->create($data);
    }

    /**
     * 更新数据
     * @param array $where
     * @param array $update
     * @return Collection
     */
    public function updateModel(array $where, array $update)
    {
        return $this->model->where($where)->update($update);
    }

    /***
     * 增加较少某个字段
     * @param array $where
     * @param string $field
     * @param int $num
     * @param int $type
     * @return mixed
     */
    public function updateChangeModel(array $where, string $field, int $num ,int $type = 1)
    {
        if($type == 1){
            //增加
            return $this->model->where($where)->increment($field,$num);
        }else{
            //减少
            return $this->model->where($where)->decrement($field,$num);
        }

    }

    /**
     * 删除数据
     * @param array $where
     */
    public function deleteModel(array $where){
        return $this->model->where($where)->delete();
    }
}
